#!/usr/bin/env python
# By: Kelcey Damage, 2012 & Kraig Amador, 2012

api_url = 'http://192.168.56.10:8096'
apiKey = 'u1pCKIGNJFUt50GBEHjhG9aWAWZtP6iqHc1jS5fTmsbgSG_Pl-g0_YaLrZ0Xl3n1NrQtMZ62B5jhn2iiXrFjqQ'
secret = 'dIiDF9kgFvTma4eml5qbATXbmg_CS6Jp2ca5R9HBDkl2Q4OIevugdwQP8YfhRNb3Q6Z0CWuJsev7yUqvZDfG7g'

import hashlib, hmac, string, base64, urllib
import json, urllib

class SignedAPICall(object):
    def __init__(self, api_url, apiKey, secret):
        self.api_url = api_url
        self.apiKey = apiKey
        self.secret = secret

    def request(self, args):
        args['apiKey'] = self.apiKey

        self.params = []
        self.__sort_request(args)
        self.__create_signature()
        self.__build_post_request()

    def __sort_request(self, args):
        keys = sorted(args.keys())

        for key in keys:
            self.params.append(key + '=' + urllib.quote_plus(args[key]))

    def __create_signature(self):
        self.query = '&'.join(self.params)
        digest = hmac.new(
            self.secret,
            msg=self.query.lower(),
            digestmod=hashlib.sha1).digest()

        self.signature = base64.b64encode(digest)

    def __build_post_request(self):
        self.query += '&signature=' + urllib.quote_plus(self.signature)
        self.value = self.api_url + '?' + self.query

class CloudStack(SignedAPICall):
    def __getattr__(self, name):
        def handlerFunction(*args, **kwargs):
            if kwargs:
                return self._make_request(name, kwargs)
            return self.__make_request(name, args[0])
        return handlerFunction

    def __http_get(self, url):
        response = urllib.urlopen(url)
        return response.read()

    def __make_request(self, command, args):
        args['response'] = 'json'
        args['command'] = command
        self.request(args)
        data = self.__http_get(self.value)
        # The response is of the format {commandresponse: actual-data}

        key = command.lower() + "response"
        return json.loads(data)[key]



#Usage
api = CloudStack(api_url, apiKey, secret)
request = {'listall': 'true'}
#stop zone
result = api.listZones(request)
if result!= {}:
    for zone in result['zone']:
	print "Disabling %s" % zone['name']
	request = {'id': zone['id'], 'allocationstate' : 'Disabled'}
	result = api.updateZone(request)
#stop vms

result = api.listVirtualMachines(request)
if result!= {}:
    #stop virtual machines
    print api.value
    for vm in result['virtualmachine']:
        print "Stopping %s" % vm['name']
	#request = {'id': vm['id']}
        request = {'id': vm['id']}
	result=api.stopVirtualMachine(request)
	#print "api url", api.value

result = api.listSystemVms(request)
if result!= {}:
    #stop system vms
    for vm in result['systemvm']:
        print "Stopping %s" % vm['name']
        #request = {'id': vm['id']}
        request = {'id': vm['id']}
        result=api.stopSystemVm(request)
	#print "api url", api.value
